import { Image, View } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import React, {
  PropsWithChildren,
  useCallback,
  useEffect,
  useState,
} from 'react';
import { ModelDetailRespType } from '@/types/modelDetail';
import Skeleton from '@/components/Skeleton';
import { getJsonFile, getSignedUrl } from '@/utils/sts';

import './index.module.scss';

const ModelDetailPage: React.FC<PropsWithChildren> = () => {
  const router = useRouter<{ model: string }>();
  const [loading, setLoading] = useState(true);
  const [modelDetail, setModelDetail] = useState<ModelDetailRespType | null>(
    null
  );

  const getModelDetail = useCallback(async () => {
    const { model } = router.params;

    if (model) {
      setLoading(true);
      const data = await getJsonFile<ModelDetailRespType>('detail/GS1002.json');

      if (!data) {
        Taro.showToast({ title: '数据获取失败', icon: 'none' });
        return;
      }
      const imageProms = [...data.images].map(item => getSignedUrl(item, 1800));
      const images = (await Promise.all(imageProms)) as string[];
      data.images = [...images];
      setModelDetail(data);
      setTimeout(() => {
        setLoading(false);
      }, 1500);
    }
  }, [router.params]);

  useEffect(() => {
    getModelDetail();
  }, []);

  return (
    <React.Fragment>
      {loading ? (
        <Skeleton />
      ) : (
        <View className='model-detail-container'>
          {modelDetail?.images.map((item, index) => (
            <Image
              key={index}
              src={item}
              mode='aspectFill'
              className='detail-image'
              onClick={() => {
                Taro.previewImage({
                  urls: modelDetail!.images,
                  current: item,
                });
              }}
            />
          ))}
        </View>
      )}
    </React.Fragment>
  );
};

export default ModelDetailPage;
